import { unref } from 'vue'
import { fmt_address, fmt_datetime, fmt_date } from '@src/filter/fmt';
import { fmt_form_cascader, formatFormFieldItem, fmt_js_code_block } from '@src/filter/form';
import * as FormUtil from './util';
import { ctiCallOut } from '@src/util/ctisdk';
import { FieldManager } from './components';
import platform from '@src/platform';
import dingTalk from '@src/util/dingtalk';
import { isQualityTimeField } from '@service/FieldService.ts'
import { isOpenData, openAccurateTab } from '@src/util/platform';
import { isArray, isEmpty } from '@src/util/type'
import { getProductQualityStatusText } from '@src/util/qualityInfoConfig'
import { ProductFieldNameMappingEnum, FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum'
import { isStringArray } from '@src/util/array.ts'
import formRichtTextView from '@src/component/form/components/FormRichText/view.vue';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
// import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum';
import { getCurrencyDisplayView } from '@src/util/currency';
import TagsModeSelect from 'src/component/form/common/components/RelationOptionsModal/TagsModeSelect/index.vue';

import { t } from '@src/locales'
import { convertQualityInfoRemoteDataToFormQualityInfoFieldValue, smoothQualityInfoFieldForFormView } from '@service/QualityInfoService'
import { useQualityInfoTableGroupFields } from '@hooks/useQualityInfo'
import BbxTimezoneTimePicker from '@src/component/Bbx/TimezoneTimePicker'
import { openTabForWikiView } from '@src/util/business/openTab'

import { toArray, useFormTimezone, isString } from 'pub-bbx-utils'
import { needRowForOneEnumInView, dontNeedMarginForBox } from 'src/component/form/util'
const { disposeFormItemViewTime } = useFormTimezone()

const link_reg = /((((https?|ftp?):(?:\/\/)?)(?:[-;:&=\+\$]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\?\+=&;:%!\/@.\w_]*)#?(?:[-\+=&;%!\?\/@.\w_]*))?)/g;

const FormView = {
  name: 'form-view',
  props: {
    mode: {
      type: String,
      default: ''
    },
    fields: {
      type: Array,
      default: () => []
    },
    value: {
      type: Object,
      default: () => ({})
    },
    bizId: {
      type: String,
      default: ''
    },
    formCellCount:{
      type: Number,
      default: 1
    },
  },
  data() {
    return {
      sectionState: {},
    }
  },
  components:{
    formRichtTextView,
    BbxTimezoneTimePicker,
    TagsModeSelect,
  },
  methods: {
    // TODO :预览图片
    previewImage(event){
      let element = event.target;
      let imgSrc = element.currentSrc;

      if ((!/\.(png|bmp|gif|jpg|jpeg|tiff|tif|jfif|ico|pcx|tga)$/i.test(imgSrc) && !imgSrc) || !element) return

      let list = event.target.closest('.ql-editor');
      let images = Array.prototype.slice.call(list.querySelectorAll('img'));

      let currIndex = 0;
      let urls = images.map((item, index) => {
        if(item == element) currIndex = index;
        return item.getAttribute('src');
      });
      platform.imagePreview({
        imageDom: list,
        currIndex,
        urls
      });  
    },
    toggleDisplay(id) {
      this.sectionState[id] = !this.sectionState[id];
    },
    /** 格式化值 */
    formatValue(field, value){
      // 多选
      if (FormUtil.isMultiSelect(field)) {
        return toArray(value).join('，')
      }

      // 日期
      if(FormUtil.isDate(field)){
        return fmt_date(value)
      }

      // 日期时间
      if(FormUtil.isDatetime(field)){
        return fmt_datetime(value)
      }
      
      // 人员
      if (field.formType === 'user') {
        // 多选
        if(Array.isArray(value)) {
          return value.map(i => i.displayName || i.name).join(',');
        }
      
        return value && (value.displayName || value.name);
      }
      
      return value;
    },
    formatUserValue(value){
      if(!value) return []
      let newVal = []
      // 多选
      if(Array.isArray(value) && value.length) {
        newVal = value.map(i =>{ return {staffId:i.staffId, userId:i.userId || i.id, userName:i.displayName || i.name}});
      } else {
        newVal = value.staffId && [{userId:value.userId, staffId:value.staffId, userName:value.displayName || value.name}]
      }
      return newVal;
    },
    buildCommonDom({displayName, value, formType}) {
      let className = {
        'form-view-row-content': true,
        'form-view-textarea-preview': formType === 'textarea'
      };
      
      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class={className}>{value}</div>
        </div>
      )
    },
    // 客户产品关联
    buildRelationUserDom({displayName, value, setting}) {
      let className = {
        'form-view-row-content': true
      };
      if(!value) return []
      let newVal = []
      if(setting.formType === 'user') {
        newVal = value.split(',')
      } else if(setting.fieldName === 'customerManager') {
        newVal = [value]
      }
      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class={className}>
            {newVal.map(staffId=><open-data type="userName" openid={staffId}></open-data>)}
          </div>
        </div>
      )
    },
    buildUserDom({displayName, value}) {
      let className = {
        'form-view-row-content': true
      }

      let content = null
      let isArrayValue = isArray(value)
      let isStringArrayValue = isStringArray(value)
      
      if (isArrayValue && isStringArrayValue) {
        content = value.map((staffId, index) => <span><open-data type="userName" openid={staffId}></open-data>{index + 1 === value.length ? '' : '，' }</span> )
      }
      else if (isArrayValue && !isStringArrayValue) {
        content = value.map((item, index) => <span><open-data type="userName" openid={item.staffId} v-user={item?.userId || ''} class="user-card-triggle"></open-data>{index + 1 === value.length ? '' : '，' }</span> )
      }
      else {
        content = value && <open-data type="userName" openid={value}></open-data>
      }
      
      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class={className}>
            { content }
          </div>
        </div>
      )
    },
    buildNormalUserDom({displayName, value}){
      let className = {
        'form-view-row-content': true
      }
      let content = null
      let isArrayValue = isArray(value)
      let isStringArrayValue = isStringArray(value)
      
      if (isArrayValue && isStringArrayValue) {
        content = value.map((name, index) => <span><span>{{name}}</span>{index + 1 === value.length ? '' : '，' }</span> )
      }
      else if (isArrayValue && !isStringArrayValue) {
        content = value.map((item, index) => <span><span v-user={item?.userId || ''} class="user-card-triggle">{item?.userName || ''}</span>{index + 1 === value.length ? '' : '，' }</span>)
      }
      else {
        content = value && <span></span>
      }
      
      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class={className}>
            { content }
          </div>
        </div>
      )
    },
    buildCustomerManagerDom({displayName, value}) {
      let className = {
        'form-view-row-content': true
      };
      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class={className}>
            {<open-data type="userName" openid={value}></open-data>}
          </div>
        </div>
      )
    },

    /**
     * 渲染质保信息字段
     * @param {*} renderFields  质保开始时间、质保结束时间、质保状态
     * @returns 
     */
    buildQualityInfoGroup(renderFields, field) {
      let className = {
        'form-view-row-content': true
      };
      return (
        <div class={this.getformItemClass(field)}>
          {renderFields.map(({displayName, value}) => (
            <div class="form-view-row bbx-form-cell-item">
              <label>{displayName}</label>
              <div class={className}>{value}</div>
            </div>
          ))}
        </div>
      )
    },

    buildAddressDom(address) {
      const { value, displayName, originalVal} = address;
      const map = {
        address: originalVal,
        title: displayName,
      };
    
      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class="form-view-row-content form-view-row-content-address" onClick={() => this.openMap(map)} >
            {value && <i class="iconfont icon-address customer-address-icon"></i>}
            <base-address-switch value={originalVal}/>
          </div>
        </div>
      )
    },

    buildPhoneDom(lmPhone) {
      const { value, displayName} = lmPhone;
      let sourceData = {};
      if(this.$route?.path?.includes('/customer/view/')){
        sourceData = {
          sourceTypeId:this.value.id,
          sourceType:'customer',
        }
      } 
      const callIconComponent = <biz-call-icon value={value} sourceData={sourceData} />
      
      // 是否展示同步按钮 （1.客户表单 2.钉钉crm 3.联系人手机号为0）
      const showSyncBtn = this.mode === 'customer' && dingTalk.inDingTalkCrm && value == 0;
      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class="form-view-row-content">
            <span ref="lmPhone">{value}</span>
            { callIconComponent }
            {
              showSyncBtn
                && <el-button type="primary" size="mini" style="margin-left: 8px;padding: 4px!important;" onClick={this.syncDtalkCrmPhone}>同步</el-button>
            }
          </div>
        </div>
      )
    },

    /** 同步钉钉crm联系人手机号 */
    async syncDtalkCrmPhone() {
      try {
        let phone = await dingTalk.getCrmData(this.value.id);
        this.$refs.lmPhone.innerText = phone;
        this.$platform.alert(t('common.form.formView.tips1'));
      } catch (error) {
        console.error(error);
        if(error) this.$platform.alert(error);
      }
    },

    async makePhoneCall(phone, hasCallCenterModule){
      if(!phone || !hasCallCenterModule) return
      try {
        ctiCallOut(phone) // taskType:"customer"
      } catch (error) {
        console.error(error);
      }
    },

    buildTextarea({displayName, value, formType, tableName}) {
      if(isArray(value)) value = value.join();
      // 工单类型的
      const newVal = (value && isString(value)) ? value.replace(link_reg, (match) => {
        return `<a href="javascript:;" url="${match}">${match}</a>`
      }) : (value || '');

      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class="form-view-row-content">
            <span domPropsInnerHTML={newVal} class="form-view-textarea-content" onClick={(e) => {
              e.stopPropagation();
              let url = e.target.getAttribute('url');

              if (!url) return;
              if (!/http/gi.test(url)) return platform.alert(t('common.base.tip.confirmHttpProtocol'));

              platform.openLink(url, false);
            }}>{newVal}</span>
          </div>
        </div>
      )
    },
    buildInfoDom(info) {
      const value = info.value;
      return (
        <div class="form-view-row">
          <div class="form-view-row-content form-view-info-content">
            <div class="form-ql-editor ql-container">
              <div class="ql-editor" domPropsInnerHTML={value} onClick={(e) => this.previewImage(e)}></div>
            </div>       
          </div>
        </div>
      )
    },
    buildAutoGraph({displayName, value}) {
      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class="form-view-row-content">
            { value && <div class="form-view-autograph-content"><img src={value} /></div> }
          </div>
        </div>
      )
    },
    buildQualityTime({ displayName, value }) {
      let timeType = value?.qualityTimeType || '';
      if(timeType == '月'){
        timeType = t('common.time.month')
      }else if(timeType == '年'){
        timeType = t('common.time.year')
      }
      return (
        <div class="form-view-row">
          <label>{ displayName }</label>
          <div class="form-view-row-content">
            { value && (
              <div class="form-view-content">
                { value?.qualityTimeNumber }
                { timeType }
              </div> 
            )}
          </div>
        </div>
      )
    },
    buildRelatedTask({displayName, value}) {
      if(Array.isArray(value) && value.length > 0) {
        let _renderContent = value.map((item, index) => {
          let taskId = item.taskId || '';
          let taskNo = item.taskNo || '';
          
          return (
            <span>
              <a href="javascript:;" class="link-text" style="margin: 0" onClick={() => {
                // this.$platform.openTab({
                //   id: `task_view_${taskId}`,
                //   title: `工单${taskNo}`,
                //   close: true,
                //   url: `/task/view/${taskId}?noHistory=1`,
                // })
                openAccurateTab({
                  type: PageRoutesTypeEnum.PageTaskView,
                  key: taskId,
                  titleKey: taskNo,
                  params: 'noHistory=1'
                })
              }}>
                {taskNo}
              </a>
              {index < value.length - 1 && ','}
            </span>
          );
        });
        
        return (            
          <div class="form-view-row">
            <label>{displayName}</label>
            <div
              class="form-view-row-content">
              {_renderContent}
            </div>
          </div>)
      }

      return (
        <div class="form-view-row">
          <label>{displayName}</label>
        </div>);
    },

    buildRelatedCustomer({displayName, value}, field) {
      if(Array.isArray(value) && value.length > 0) {
        let _renderContent = value.map((item, index) => {
          let customerId = item.id || '';
          let customerName = item.name || '';
          return (
            <span>
              <a href="javascript:;" class="link-text" style="margin: 0" onClick={() => {
                // this.$platform.openTab({
                //   id: `customer_view_${customerId}`,
                //   title: '客户详情',
                //   close: true,
                //   url: `/customer/view/${customerId}?sourceCustomerId=${this.value.id}&fieldName=${field.fieldName}&noHistory=1`,
                // });
                openAccurateTab({
                  type: PageRoutesTypeEnum.PageCustomerView,
                  key: customerId,
                  params: `sourceCustomerId=${this.value.id}&fieldName=${field.fieldName}&noHistory=1`
                })
              }}>
                {customerName}
              </a>
              {index < value.length - 1 && ','}
            </span>
          );
        });
        
        return (            
          <div class="form-view-row">
            <label>{displayName}</label>
            <div
              class="form-view-row-content">
              {_renderContent}
            </div>
          </div>)
      }

      return (
        <div class="form-view-row">
          <label>{displayName}</label>
        </div>);
    },
    buildRelationWiki(field, value) {
      const displayName = field.displayName
      if(Array.isArray(value) && value.length > 0) {
        let _renderContent = value.map((item, index) => {
          let wikiId = item.id || '';
          let wikiName = item.name || '';
          return (
            <span>
              <a href="javascript:;" class="link-text" style="margin: 0" onClick={() => {
                openTabForWikiView(wikiId);
              }}>
                {wikiName}
              </a>
              {index < value.length - 1 && ','}
            </span>
          );
        });

        return (
          <div class="form-view-row">
            <label>{displayName}</label>
            <div
              class="form-view-row-content">
              {_renderContent}
            </div>
          </div>)
      }

      return (
        <div class="form-view-row">
          <label>{displayName}</label>
        </div>);
    },

    buildRelationMaterial({displayName, value}) {
      let id = value?.materielId || '';

      return (            
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class="form-view-row-content">
            <a href="javascript:;" class="link-text" style="margin: 0" onClick={() => {
              openAccurateTab({
                type: PageRoutesTypeEnum.PageItemsDetail,
                key: id,
                params: `id=${id}`
              })
            }}>
              {value?.materielName || ''}
            </a>
          </div>
        </div>)
    },
    buildRichText({displayName, value}, field){
      return (            
        <div class="form-view-row al-s">
          <label>{displayName}</label>
          <div
            class="form-view-row-content">
            <formRichtTextView field={{...field, disabled:true}} value={value}></formRichtTextView>
            {/* <form-richtext field={{...field, disabled:true}} value={value} readonly={true} ></form-richtext> */}
          </div>
        </div>)
    },

    buildCurrencyDom({displayName, value}) {
      return  (            
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class="form-view-row-content">
            { getCurrencyDisplayView(value) }
          </div>
        </div>)
    },
    buildTagsModeSelect(field, value) {
      return (
        <div class="form-view-row">
          <label>{field.displayName}</label>
          <TagsModeSelect field={field} value={value} />
        </div>
      )
    },

    openMap({address, title}) {
      if (!address) return;
      this.$fast.map.display(address, {title })
        .catch(err => console.error('openMap catch an err: ', err));
    },
  
    mapFieldToDom(field, createElement) {
      let {formType, fieldName, displayName, isSystem, isHidden, isVisible, setting} = field;
      if (formType === 'separator') {
        const groups = FormUtil.groupField(this.fields, this.value, true)
        const isHiddenSeparator = FormUtil.isHiddenSeparator(groups, this.value, this.fields, fieldName, false)
        // 当前分割线分组字段都不显示时，分割线不显示
        if (isHiddenSeparator) return null
        const cn = `iconfont icon-fdn-select ${!this.sectionState[field.id] && 'reversal'}`;
        return displayName ? (
          <h4 class={`section-title ${this.formCellCount > 1 ? 'mar-r-12-i' : ''}`} >
            {displayName}
            <i class={cn} onClick={() => this.toggleDisplay(field.id)}></i>
          </h4>
        ) : null;
      }
      // 如果为隐藏的字段不显示
      if(isHidden == 1) return null;

      // 判断是否可见
      if(isVisible == false) return null;    
      
      let originalObj = this.value;

      // 项目管理任务表单特殊处理
      if (field.tableName === 'mission') {
        originalObj.attribute = originalObj?.taskAttribute || {}
      }

      let params = {};
      let value = isSystem ? originalObj[fieldName] : originalObj?.attribute && originalObj?.attribute[fieldName];

      if(fieldName === 'quality'){
        // 质保时间处理
        // 根据质保信息拆分质保开始时间、质保结束时间、质保状态字段
        const qualityFields = unref(useQualityInfoTableGroupFields(field))
        // 后端字段转前端字段 fieldName与qualityFields一致
        const infoData = convertQualityInfoRemoteDataToFormQualityInfoFieldValue(originalObj.qualityInfo)
        // 根据字段拆分要渲染信息
        const renderFields = qualityFields.map(item => {
          // 初始时间
          const itemValue = disposeFormItemViewTime(item, infoData[item.fieldName])
          return {
            displayName: item.displayName,
            value: formatFormFieldItem(item, itemValue) // 格式化值
          }
        })
        // 渲染表单
        return this.buildQualityInfoGroup(renderFields, field)
      }

      value = disposeFormItemViewTime(field, value) // 回显国际化时间处理

      params = {displayName, value, formType};
      // 关联工单
      if (formType === 'relationForm') {
        let data = []
        if (this.value?.subForms) {
          const list = this.value?.subForms || []
          list.forEach(item => {
            if(item?.attribute?.parentFieldName && fieldName === item.attribute.parentFieldName){
              data.push(item.attribute)
            }
          })
        }
        value = data;
      }

      if(this.$slots[fieldName]) {
        return this.$slots[fieldName];
      }

      // return slot
      if (this.$scopedSlots[fieldName]) {
        return this.$scopedSlots[fieldName]({displayName, value, formType, field});
      }

      if(['date', 'datetime'].includes(formType)){
        const format = useFormTimezone().getFormDateFormat(formType, setting?.dateType)
        params.value = value ? (
          <bbx-timezone-time-picker
            field={field}
            value={value}
            is-edit={false}
            format={format}
            valueFormat={format}
          > 
          </bbx-timezone-time-picker>
        ) : null
        return (<div class={this.getformItemClass(field)}>{this.buildCommonDom(params)}</div>)
      }

      // empty slot
      const isValueEmpty = this.isValueEmpty(value, formType);
      const emptySlot = this.$scopedSlots.empty;
      if (isValueEmpty && emptySlot) {
        return emptySlot({
          displayName,
          value,
          formType,
          field
        });
      }
      
      // 加密字段
      if (value == '***') return (<div class={this.getformItemClass(field)}>{this.buildCommonDom(params)}</div>);
      
      // 客户产品关联
      let isUser = setting && (setting.formType === 'user' || setting.fieldName === 'customerManager') 
      if (isOpenData && (formType === 'relationCustomer' || formType === 'relationProduct') && isUser) {
        params = {
          ...params,
          value, 
          setting
        };
        return (<div class={this.getformItemClass(field)}>{this.buildRelationUserDom(params)}</div>);
      }

      // 电子签名、客户签名
      if (formType === 'autograph' || formType === 'systemAutograph') {
        params = {
          ...params,
          value
        };
        return (<div class={this.getformItemClass(field)}>{this.buildAutoGraph(params)}</div>);
      }

      if (formType === 'richtext') {
        params = {
          ...params,
          value
        }
        return (<div class={this.getformItemClass(field)}>{this.buildRichText(params, field)}</div>)
      }

      if (formType === 'knowledge' && field.tableName === 'solutionTemplate') {
        let wikiDataValue = originalObj[fieldName] || originalObj.attribute?.[fieldName] || originalObj.wikiDataValue || []
        wikiDataValue = wikiDataValue.map(v => ({id: v.id, name: v.attribute?.title}))
        return (<div class={this.getformItemClass(field)}>{this.buildRelationWiki(field, wikiDataValue)}</div>)
      }
      if ((['subSparePart', 'subServiceItem', 'subMaterials']).includes(formType) && field.tableName === 'solutionTemplate') {
        const obj = {
          'subSparePart': 'sparePartValue',
          'subServiceItem': 'serviceProjectsValue',
          'subMaterials': 'materialValue',
        };
        const subData = originalObj[fieldName] || originalObj.attribute?.[fieldName] || originalObj[obj[formType]] || []
        value = subData.map(data => {
          const { id, detailId, attribute } = data
          return { id: detailId, editId: id, ...attribute }
        })
      }

      // 组件默认视图
      let FormField = FieldManager.findField(field.formType);
      if(FormField && FormField.view){
        let attrs = {
          props: { 
            field, 
            value, 
            originValue: this.value,
            mode: this.mode,
            bizId: this.bizId
          }
        }

        return (<div class={this.getformItemClass(field)}>{createElement(FormField.view, attrs)}</div>);
      }

      if (formType === 'attachment' || formType === 'receiptAttachment') {
        params = {
          ...params,
          value: toArray(value).map(a => <base-file-item file={a} Source={toArray(value)} readonly key={a.id}/>)
        };
      }
      
      if (formType === 'select' && field?.setting?.selectType == 3) {
        // 渲染标签模式下拉
        return (<div class={this.getformItemClass(field)}>{this.buildTagsModeSelect(field,value)}</div>)
      }

      if (formType === 'select' && field?.setting?.isMulti) {
        // 部分旧数据存在isMulti = true，但是value是字符串的问题
        const formatValue = Array.isArray(value) ? value : isEmpty(value) ? [] : [value];
        params = {
          ...params,
          value: toArray(formatValue).join('，')
        };
      }
      
      if (formType === 'tags') {
        params = {
          ...params,
          value: toArray(value).map(t => t.tagName).join(' ')
        };
      }
      
      if (formType === 'select' && fieldName === 'tags') {
        params = {
          ...params,
          value: toArray(value).map(tag => tag.tagName).join('，')
        };
      }

      if (fieldName === ProductFieldNameMappingEnum.QualityInfoStatus) {
        const status = getProductQualityStatusText(value)
        params = {
          ...params,
          value: status
        };
      }
      
      if (formType === 'user') {
        if(isOpenData) {
          params = {
            ...params,
            value: this.formatUserValue(value)
          }
          
          return this.buildUserDom(params);
        }
        params = {
          ...params,
          value: this.formatUserValue(value)
        }
        return (<div class={this.getformItemClass(field)}>{this.buildNormalUserDom(params)}</div>);

      }
      
      if (formType === 'user' && fieldName === 'manager') {
        params = {
          ...params,
          value: this.value.customerManagerName
        };
        if(isOpenData) {
          params = {
            ...params,
            value: this.value.customerManagerStaffId || ''
          }
          return (<div class={this.getformItemClass(field)}>{this.buildCustomerManagerDom(params)}</div>);
        }
      }

      if (formType === 'user' && fieldName === 'productManager') {
        params = {
          ...params,
          value: this.value.productManagerName
        };
        if(isOpenData) {
          params = {
            ...params,
            value: this.value.productManagerStaffId || ''
          }
          return (<div class={this.getformItemClass(field)}>{this.buildCustomerManagerDom(params)}</div>);
        }
      }
  
      if (formType === 'address' || formType === 'customerAddress') {
        params = {
          ...params,
          value: fmt_address(value),
          originalVal: value
        };
        
        return (<div class={this.getformItemClass(field)}>{this.buildAddressDom(params)}</div>);
      }
      
      if (formType === 'phone') {
        params = {
          ...params,
          value,
        };
        
        return (<div class={this.getformItemClass(field)}>{this.buildPhoneDom(params)}</div>);
      }

      if (formType == 'info') {
        params = {
          ...params,
          value: field.placeHolder
        };
        return (<div class={this.getformItemClass(field)}>{this.buildInfoDom(params)}</div>);
      }

      // 多行文本、客户关联字段、产品关联字段
      if(formType === 'textarea') {
        params = {
          ...params,
          value
        };
        return (<div class={this.getformItemClass(field)}>{this.buildTextarea(params)}</div>);
      }

      if(['relationCustomer', 'relationProduct'].includes(formType)) {
        let {isMulti, displayMode, formType: originalFormType, module} = field.setting || {}

        let tableName = field.tableName
        if (field.tableName !== 'register' && originalFormType === 'cascader') {
          if (module === 'product' && (field.tableName === 'task' || field.tableName === 'event')) {
            if (Array.isArray(value)) {
              // 新数据处理
              value = (value || []).map(item => fmt_form_cascader(item, isMulti)).join('、')
            } else {
              // 老数据处理
              value = fmt_form_cascader(value, isMulti, displayMode)
            }
          } else {
            value = fmt_form_cascader(value, isMulti, displayMode)
          }
        }
        params = { ...params, value, tableName };
        return (<div class={this.getformItemClass(field)}>{this.buildTextarea(params)}</div>);
      }

      if (formType === 'cascader') {
        params = {
          ...params,
          value: fmt_form_cascader(value, !!field?.setting?.isMulti, field?.setting?.displayMode), // toArray(value).join(field?.setting?.isMulti ? "，" : "/")
        };
      }

      if (formType === 'timestamp') {
        params = {
          ...params,
          value: fmt_datetime(value)
        };
      }

      if(formType === 'related_task') {
        params = {
          ...params,
          value
        };
        return (<div class={this.getformItemClass(field)}>{this.buildRelatedTask(params)}</div>);
      }

      // 关联客户
      if (formType === 'related_customers') {
        params = {
          ...params,
          value
        }
        return (<div class={this.getformItemClass(field)}>{this.buildRelatedCustomer(params, field)}</div>)
      }

      
      if (isQualityTimeField(field)) {
        params = {
          ...params,
          value
        }
        
        return (<div class={this.getformItemClass(field)}>{this.buildQualityTime(params)}</div>)
      }
      // 处理工程师资质回显的value数据
      if (formType === 'engineerQualification') {
        params = {
          ...params,
          value: toArray(value).join('，')
        };
      }
      
      // 产品关联物料
      if (formType === 'relationMaterials') {
        params = {
          ...params,
          value
        }
        return (<div class={this.getformItemClass(field)}>{this.buildRelationMaterial(params)}</div>)
      }

      // 国际货币金额
      if (formType === 'currency') {
        params = {
          ...params,
          value
        }
        return (<div class={this.getformItemClass(field)}>{this.buildCurrencyDom(params)}</div>)
      }

      // 关联服务项目
      if (formType === 'relatedServiceItem') {
        params = {
          ...params,
          value: toArray(value).map(t => t.name).join('，')
        };
      }

      // 关联服务项目
      if (formType === 'jsCodeBlock') {
        params = {
          ...params,
          value: fmt_js_code_block(value)
        };
      }

      // other types: text date number datetime phone
      return (<div class={this.getformItemClass(field)}>{this.buildCommonDom(params)}</div>);
    },
    /**
       * @description 判断字段值是否为空
      */
    isValueEmpty(value, formType) {
      // 物流
      const logisticsField = formType == FieldTypeMappingEnum.Logistics;

      if (logisticsField) {
        return isEmpty(value) || isEmpty(value?.[0]?.id);
      }

      return isEmpty(value);
    },
    getformItemClass(field, isSlot = false){
      let formItemClass = [`bbx-form-item-view-${field.formType}`];
      if(field?.formType && !needRowForOneEnumInView.includes(field.formType) && !isSlot){
        formItemClass.push('bbx-form-cell-item')
      }else{
        formItemClass.push('bbx-form-item')
      }
      formItemClass.push(`bbx-from-item-cell-box-${this.formCellCount}`)
      if(this.formCellCount > 1){
        if(!dontNeedMarginForBox.includes(field.formType)){
          formItemClass.push('mar-r-12')
        }
        
      }
      
      return formItemClass.join(' ')
    },
    /**
     * 初步渲染时候判断是否显示分隔符
     * @param {*} field
     * @returns {boolean}
     */
    isHiddenFiledInit(field) {
      let {formType, fieldName, displayName, isSystem, isHidden, isVisible, setting} = field;
      if (formType === 'separator') {
        const groups = FormUtil.groupField(this.fields, this.value, true)
        const isHiddenSeparator = FormUtil.isHiddenSeparator(groups, this.value, this.fields, fieldName, false)
        return isHiddenSeparator
      }
    }
  },
  render(createElement) {
    if (!this.fields.length) {
      console.warn('[FormView] fields is empty');
      return null;
    }
    // 初步分组
    let preliminaryGroups = FormUtil.groupField(this.fields, this.value, false);
    // 分隔符的显示改变分组的排列方式变量
    let isHiddenSeparatorChangeGroups = preliminaryGroups.every(group => {
      return group.filter(f => f.formType === 'separator').every(item => this.isHiddenFiledInit(item))
    })

    let groups
    // 如果分隔符不隐藏就走原来的，如果隐藏就不分组
    if (!isHiddenSeparatorChangeGroups) {
      groups = FormUtil.groupField(this.fields, this.value, false);
    } else {
      groups = FormUtil.noGroup(this.fields, this.value, false);
    }
    let domGroups = groups.map(group => {
      let currentGroupId = 0;
      let title = group.filter(f => f.formType === 'separator').map(item => {
        currentGroupId = item.id;
        if (this.sectionState[currentGroupId] === undefined) {
          this.$set(this.sectionState, currentGroupId, true);
        }
        return this.mapFieldToDom(item, createElement);
      });
      let items = group.filter(f => f.formType !== 'separator').map(item => 
        this.mapFieldToDom(item, createElement)
      );

      return (
        <div class={'view-group'}>
          {title}
          <div class={`items-of-group bbx-cell-form-box-${this.formCellCount}`}>{
            (this.sectionState[currentGroupId] !== false) && items
          }</div>
        </div>
      );
    });
    
    return (
      <div class={'form-view bbx-cell-form-box'}>
        {domGroups}
      </div>
    )
  },
};

export default FormView;
